<script setup lang="ts">
import { LockOutlined, MailOutlined, MobileOutlined, UserOutlined } from '@ant-design/icons-vue'
import { AxiosError } from 'axios'
import { ref } from 'vue'
import GlobalLayoutFooter from '~/layouts/components/global-footer/index.vue'
import { loginApi } from '~/api/common/login'
import { getPasswordCaptcha, getPhoneCaptcha, getPhoneCode, getPublicKey } from '~@/api/auth'
import { getQueryParam } from '~/utils/tools'
import type { CaptchaModel } from '~@/api/common/login'
import { ResponseCode } from '~@/api/response.code'
import { encryptByRSA } from '~@/utils/crypto'
// TODO 替换成自己的微信公众号相关信息
const appid = ''
const redirectUrl = ''
const wechatQrUrl = `https://open.weixin.qq.com/connect/qrconnect?appid=${appid}&scope=snsapi_login,snsapi_userinfo&redirect_uri=${redirectUrl}&state=123456&login_type=jssdk&self_redirect=false&styletype=&sizetype=&bgcolor=&rst=&style=black`
let publicKey: string = ''
const phoneCaptcha = ref<CaptchaModel>({ captchaId: '', imageData: '' } as CaptchaModel)
const passwordCaptcha = ref<CaptchaModel>({ captchaId: '', imageData: '' } as CaptchaModel)
const messageTip = useMessage()
const notification = useNotification()
const appStore = useAppStore()
const { layoutSetting } = storeToRefs(appStore)
const router = useRouter()
const token = useAuthorization()
const loginModel = reactive({
  username: undefined,
  password: undefined,
  captcha: undefined,
  mobile: undefined,
  code: undefined,
  type: 'account',
  remember: true,
})
const { t } = useI18nLocale()
const formRef = shallowRef()
const codeLoading = shallowRef(false)
const resetCounter = 60
const submitLoading = shallowRef(false)
const errorAlert = shallowRef(false)

const { counter, pause, reset, resume, isActive } = useInterval(1000, {
  controls: true,
  immediate: false,
  callback(count) {
    if (count) {
      if (count === resetCounter)
        pause()
    }
  },
})
async function getCode() {
  codeLoading.value = true
  try {
    await formRef.value.validateFields(['mobile', 'captcha'])
    if (!(phoneCaptcha.value || passwordCaptcha.value)) {
      messageTip.error('请先获取验证码')
      return
    }

    const { code, message } = await getPhoneCode(loginModel.mobile, loginModel.captcha, phoneCaptcha?.value.captchaId)
    if (code === ResponseCode.SUCCESS) {
      reset()
      resume()
      messageTip.success('验证码发送成功，请注意查收')
    }
    else {
      messageTip.error(message || '发送失败，未知原因')
    }
    codeLoading.value = false
  }
  catch (error) {
    // TODO
    codeLoading.value = false
  }
}

async function loadPublicKey() {
  const res = await getPublicKey()
  if (res && res.code === ResponseCode.SUCCESS) {
    if (res.data)
      publicKey = res.data
  }
}

function refreshPasswordCaptcha() {
  getPasswordCaptcha().then((res) => {
    if (res && res.code === ResponseCode.SUCCESS) {
      if (res.data)
        passwordCaptcha.value = res.data
      else
        passwordCaptcha.value = { captchaId: '', imageData: '' } as CaptchaModel
    }
  })
}

function refreshPhoneCaptcha() {
  getPhoneCaptcha().then((res) => {
    console.log(res)
    if (res && res.code === ResponseCode.SUCCESS) {
      if (res.data)
        phoneCaptcha.value = res.data
      else
        phoneCaptcha.value = { captchaId: '', imageData: '' } as CaptchaModel
    }
  })
}

function tabChanged(event: any) {
  console.log(event)
  if (event === 'mobile')
    refreshPhoneCaptcha()
  else if (event === 'account')
    refreshPasswordCaptcha()
}

async function submit() {
  submitLoading.value = true
  try {
    await formRef.value?.validate()
    const params = new FormData()

    if (loginModel.type === 'account') {
      params.append('username', encryptByRSA(publicKey, loginModel.username || '') as string)
      params.append('password', encryptByRSA(publicKey, loginModel.password || '') as string)
      params.append('captcha', encryptByRSA(publicKey, loginModel.captcha || '') as string)
      params.append('captchaId', encryptByRSA(publicKey, passwordCaptcha.value?.captchaId || '') as string)
    }
    else {
      params.append('mobile', encryptByRSA(publicKey, loginModel.mobile || '') as string)
      params.append('code', encryptByRSA(publicKey, loginModel.code || '') as string)
    }
    const { data, message } = await loginApi(loginModel.type, params)
    if (data) {
      token.value = `Bearer ${data}`
      notification.success({
        message: '登录成功',
        description: '欢迎回来！',
        duration: 3,
      })
      // 获取当前是否存在重定向的链接，如果存在就走重定向的地址
      const redirect = getQueryParam('redirect', '/')
      router.push({
        path: redirect,
        replace: true,
      })
    }
    else {
      notification.error({
        message: '登录失败',
        description: message || '未知原因',
        duration: 3,
      })
    }
  }
  catch (e) {
    if (e instanceof AxiosError)
      errorAlert.value = true
  }
  submitLoading.value = false
}
onMounted(() => {
  loadPublicKey()
  refreshPasswordCaptcha()
})
</script>

<template>
  <div class="login-container">
    <div class="login-lang" flex="~" items-center justify-end gap-2 px-24px>
      <span
        flex items-center justify-center cursor-pointer text-16px
        @click="appStore.toggleTheme(layoutSetting.theme === 'dark' ? 'light' : 'dark')"
      >
        <!-- 亮色和暗黑模式切换按钮 -->
        <template v-if="layoutSetting.theme === 'light'">
          <carbon-moon />
        </template>
        <template v-else>
          <carbon-sun />
        </template>
        <SelectLang />
      </span>
    </div>
    <div class="login-content">
      <div class="ant-pro-form-login-container">
        <div class="ant-pro-form-login-top">
          <div class="ant-pro-form-login-header">
            <span class="ant-pro-form-login-logo">
              <img src="/logo-color.svg">
            </span>
            <span class="ant-pro-form-login-title">
              Ukulele
            </span>
          </div>
          <div class="ant-pro-form-login-desc">
            {{ t("pages.layouts.userLayout.title") }}
          </div>
        </div>
        <div class="ant-pro-form-login-main" w-335px>
          <a-form ref="formRef" :model="loginModel">
            <a-tabs v-model:activeKey="loginModel.type" centered @change="tabChanged">
              <a-tab-pane key="account" :tab="t('pages.login.accountLogin.tab')" />
              <a-tab-pane key="mobile" :tab="t('pages.login.phoneLogin.tab')" />
              <a-tab-pane key="wechat" :tab="t('pages.login.wechat.tab')" />
            </a-tabs>
            <!-- 判断是否存在error -->
            <a-alert
              v-if="errorAlert && loginModel.type === 'account'" mb-24px
              :message="t('pages.login.accountLogin.errorMessage')" type="error" show-icon
            />
            <a-alert
              v-if="errorAlert && loginModel.type === 'mobile'" mb-24px
              :message="t('pages.login.phoneLogin.errorMessage')" type="error" show-icon
            />
            <template v-if="loginModel.type === 'account'">
              <a-form-item
                name="username"
                :rules="[{ required: true, message: t('pages.login.username.required') }]"
              >
                <a-input
                  v-model:value="loginModel.username" allow-clear autocomplete="on"
                  :placeholder="t('pages.login.username.placeholder')" size="large"
                  @press-enter="submit"
                >
                  <template #prefix>
                    <UserOutlined />
                  </template>
                </a-input>
              </a-form-item>
              <a-form-item
                name="password"
                :rules="[{ required: true, message: t('pages.login.password.required') }]"
              >
                <a-input-password
                  v-model:value="loginModel.password" allow-clear autocomplete="off"
                  :placeholder="t('pages.login.password.placeholder')" size="large"
                  @press-enter="submit"
                >
                  <template #prefix>
                    <LockOutlined />
                  </template>
                </a-input-password>
              </a-form-item>
              <a-form-item
                name="captcha"
                :rules="[{ required: true, message: t('pages.login.captcha.required') }]"
              >
                <a-row :gutter="16">
                  <a-col :span="16">
                    <a-input
                      v-model:value="loginModel.captcha" autocomplete="off"
                      style="flex: 1 1 0%; transition: width 0.3s ease 0s; margin-right: 8px;"
                      allow-clear :placeholder="t('pages.login.captcha.placeholder')" size="large"
                      @press-enter="submit"
                    >
                      <template #prefix>
                        <MailOutlined />
                      </template>
                    </a-input>
                  </a-col>
                  <a-col :span="8">
                    <a-image
                      v-if="passwordCaptcha.imageData" width="100%" :height="40"
                      :preview="false" :src="passwordCaptcha.imageData"
                      @click="refreshPasswordCaptcha()"
                    />
                  </a-col>
                </a-row>
              </a-form-item>
            </template>
            <template v-if="loginModel.type === 'mobile'">
              <a-form-item
                name="mobile" :rules="[
                  { required: true, message: t('pages.login.phoneNumber.required') },
                  {
                    pattern: /^(86)?1([38][0-9]|4[579]|5[0-35-9]|6[6]|7[0135678]|9[89])[0-9]{8}$/,
                    message: t('pages.login.phoneNumber.invalid'),
                  },
                ]"
              >
                <a-input
                  v-model:value="loginModel.mobile" allow-clear autocomplete="on"
                  :placeholder="t('pages.login.phoneNumber.placeholder')" size="large"
                  @press-enter="submit"
                >
                  <template #prefix>
                    <MobileOutlined />
                  </template>
                </a-input>
              </a-form-item>
              <a-form-item
                name="captcha"
                :rules="[{ required: true, message: t('pages.login.captcha.required') }]"
              >
                <a-row :gutter="16">
                  <a-col :span="16">
                    <a-input
                      v-model:value="loginModel.captcha" autocomplete="off"
                      style="flex: 1 1 0%; transition: width 0.3s ease 0s; margin-right: 8px;"
                      allow-clear :placeholder="t('pages.login.captcha.placeholder')" size="large"
                      @press-enter="submit"
                    >
                      <template #prefix>
                        <MailOutlined />
                      </template>
                    </a-input>
                  </a-col>
                  <a-col :span="8">
                    <a-image
                      v-if="phoneCaptcha.imageData" :height="40" width="100%"
                      :preview="false" :src="phoneCaptcha.imageData"
                      @click="refreshPhoneCaptcha()"
                    />
                  </a-col>
                </a-row>
              </a-form-item>
              <a-form-item
                name="code"
                :rules="[{ required: true, message: t('pages.login.captcha.required') }]"
              >
                <div flex items-center>
                  <a-input
                    v-model:value="loginModel.code" autocomplete="off"
                    style="flex: 1 1 0%; transition: width 0.3s ease 0s; margin-right: 8px;"
                    allow-clear :placeholder="t('pages.login.captcha.placeholder')" size="large"
                    @press-enter="submit"
                  >
                    <template #prefix>
                      <LockOutlined />
                    </template>
                  </a-input>
                  <a-button :loading="codeLoading" :disabled="isActive" size="large" @click="getCode">
                    <template v-if="!isActive">
                      {{ t('pages.login.phoneLogin.getVerificationCode') }}
                    </template>
                    <template v-else>
                      {{ resetCounter - counter }} {{ t('pages.getCaptchaSecondText') }}
                    </template>
                  </a-button>
                </div>
              </a-form-item>
            </template>
            <template v-if="loginModel.type === 'wechat'">
              <a-form-item>
                <div style="text-align: center">
                  <iframe
                    :src="wechatQrUrl" frameborder="0" scrolling="noe" width="300px"
                    height="400px"
                  />
                </div>
              </a-form-item>
            </template>
            <div v-if="loginModel.type !== 'wechat'" class="mb-24px" flex items-center justify-between>
              <a-checkbox v-model:checked="loginModel.remember">
                {{ t('pages.login.rememberMe') }}
              </a-checkbox>
              <a>{{ t('pages.login.forgotPassword') }}</a>
            </div>
            <a-button
              v-if="loginModel.type !== 'wechat'" type="primary" block :loading="submitLoading"
              size="large" @click="submit"
            >
              {{ t('pages.login.submit') }}
            </a-button>
          </a-form>
        </div>
      </div>
    </div>
    <div py-24px px-50px :data-theme="layoutSetting.theme" text-14px>
      <GlobalLayoutFooter :copyright="layoutSetting.copyright">
        <template #renderFooterLinks>
          <footer-links />
        </template>
      </GlobalLayoutFooter>
    </div>
  </div>
</template>

<style lang="less" scoped>
.login-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    overflow: auto;
    background: var(--bg-color-container);
}

.login-lang {
    width: 100%;
    height: 40px;
    line-height: 44px;
}

.login-content {
    flex: 1 1;
    padding: 32px 0
}

.ant-pro-form-login-container {
    display: flex;
    flex: 1 1;
    flex-direction: column;
    height: 100%;
    padding: 32px 0;
    overflow: auto;
    background: inherit
}

.ant-pro-form-login-top {
    text-align: center
}

.ant-pro-form-login-header {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 44px;
    line-height: 44px
}

.ant-pro-form-login-header a {
    text-decoration: none
}

.ant-pro-form-login-title {
    position: relative;
    top: 2px;
    color: var(--text-color);
    font-weight: 600;
    font-size: 33px
}

.ant-pro-form-login-logo {
    width: 44px;
    height: 44px;
    margin-right: 16px;
    vertical-align: top
}

.ant-pro-form-login-logo img {
    width: 100%
}

.ant-pro-form-login-desc {
    margin-top: 12px;
    margin-bottom: 40px;
    color: var(--text-color-1);
    font-size: 14px
}

.ant-pro-form-login-main {
    min-width: 328px;
    max-width: 500px;
    margin: 0 auto;

    .ant-tabs-nav-list {
        margin: 0 auto;
        font-size: 16px;
    }

    .ant-pro-form-login-other {
        margin-top: 24px;
        line-height: 22px;
        text-align: left
    }

    .icon {
        margin-left: 8px;
        color: var(--text-color-2);
        font-size: 24px;
        vertical-align: middle;
        cursor: pointer;
        transition: color .3s;

        &:hover {
            color: var(--pro-ant-color-primary);
        }
    }
}

@media(min-width: 768px) {
    .login-container {
        background-image: url(https://gw.alipayobjects.com/zos/rmsportal/TVYTbAXWheQpRcWDaDMu.svg);
        background-repeat: no-repeat;
        background-position: center 110px;
        background-size: 100%;
    }

    .login-content {
        padding: 32px 0 24px;
    }

    .ant-pro-form-login-container {
        padding: 32px 0 24px;
        background-repeat: no-repeat;
        background-position: center 110px;
        background-size: 100%
    }
}
</style>~@/api/auth/public~@/api/auth
